﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Business;
using blackhouse.JavaScript.JQuery;
using blackhouse.Web.FasterFiles;

namespace blackhouse.BlackApart.Web.Modules {
	public partial class Gallery : System.Web.UI.UserControl {

		#region Fields

		private IApartmentPhoto[] photos;
		private IApartmentGroup displayApartmentGroup;

		#endregion

		#region Properties

		public string CssClass { get; set; }

		#endregion

		#region Event Handlers

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			this.SetInstance();
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.PopulateControls();
			this.AddJsFiles();
		}

		protected void rptGallery_ItemDataBound(object sender, RepeaterItemEventArgs e) {
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
				IApartmentPhoto photo = e.Item.DataItem as IApartmentPhoto;
				HyperLink lnkGallery = e.Item.FindControl("lnkGallery") as HyperLink;
				if (photo != null && lnkGallery != null) {
					ImageUtils.ApartmentPhotoGalleryImage(lnkGallery, photo, this.displayApartmentGroup);
				}
			}
		}

		#endregion

		#region Methods

		private void SetInstance() {
			DisplayApartmentTypeState state = DisplayApartmentTypeState.GetCurrentState();
			if (state != null && state.ApartmentType != null) {
				this.photos = Factory.Instance().GetApartmentPhoto().GetApartmentTypePhotos(state.ApartmentType.Id);
				this.displayApartmentGroup = state.ApartmentType;
			}
		}

		private void PopulateControls() {
			if (this.photos != null && this.photos.Length > 0) {
				this.rptGallery.DataSource = this.photos;
				this.rptGallery.DataBind();

				if (!string.IsNullOrEmpty(this.CssClass)) {
					if (!string.IsNullOrEmpty(this.pnlGallery.CssClass))
						this.pnlGallery.CssClass = this.CssClass;
					else
						this.pnlGallery.CssClass += " " + this.CssClass;
				}
			}
			else {
				this.pnlGallery.Visible = false;
			}
		}

		private void AddJsFiles() {
			ClientScriptManager jsManager = Page.ClientScript;
			string scriptName = "prettyPhoto";
			string scriptSrc = "/prettyphoto/js/jquery.prettyPhoto.js";
			if (!jsManager.IsClientScriptIncludeRegistered(scriptName)) {
				jsManager.RegisterClientScriptInclude(scriptName, scriptSrc);
			}

			JQueryLibraries jql = new JQueryLibraries();
			jql.IncludeFileBasedOnJQuery("blackhouse.BlackApart.Web.JavaScript.gallery.js,blackhouse.BlackApart.Web");
			FasterFilesProvider ffp = new FasterFilesProvider();
			ffp.AddAfterScript(string.Format("SetGallery('#{0}');", this.pnlGallery.ClientID));
		}

		#endregion

	}
}